package com.webvihar.access2db.services;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;

import com.google.gson.Gson;
import com.webvihar.access2db.model.JsonObject;
import com.webvihar.access2db.utils.Base64Coder;

@Path("/runQuery")
public class ExecuteQuery {

	// This method is called if Application/JSON is request
	@POST
	@Produces(MediaType.APPLICATION_JSON)
	public String runResponse(@QueryParam("encoded")Boolean base64encode, @QueryParam("host")String host, @QueryParam("port")String port, @QueryParam("username")String username, @QueryParam("password")String password, @QueryParam("dbname")String dbname, @QueryParam("query")String query) {
		int queryResult = -1;
		String meta = "";
		String error = "";
		// Decode the data if it is in encoded format
		if(base64encode) {
			host = Base64Coder.decodeString(host);
			port = Base64Coder.decodeString(port);
			username = Base64Coder.decodeString(username);
			password = Base64Coder.decodeString(password);
			dbname = Base64Coder.decodeString(dbname);
			query = Base64Coder.decodeString(query);
			System.out.println("Query\t:\t"+query);
		}
		try {
			Class.forName("com.mysql.jdbc.Driver").newInstance();
			String conString = "jdbc:mysql://"+host+":"+port+"/"+dbname;
			System.out.println("Connection String\t:\t"+conString);
			Connection con = DriverManager.getConnection(conString, username, password);
			Statement stmt = con.createStatement();
			queryResult = stmt.executeUpdate(query);
		} catch(Exception e) {
			e.printStackTrace();
			error = e.getMessage();
		}

		JsonObject<String> response = new JsonObject<String>(0, getResultstring(queryResult), meta, error);
		Gson gson = new Gson();
		String responseJson = gson.toJson(response);

		return responseJson;
	}

	public String getResultstring(int result) {
		if(result > 0) {
			return (result > 1) ? result+" rows have been affected..." : result + " row is affected...";
		} else if( result == 0) {
			return "Query executed successfully...";
		} else {
			return "Query execution failed...";
		}
	}

}
